package cn.amaake.magicplugin.rpc.modules;

import cn.amaake.magicplugin.rpc.model.RpcJsonBean;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.rpc.service.GenericService;
import org.springframework.context.ApplicationContext;
import org.ssssssss.magicapi.core.annotation.MagicModule;
import org.ssssssss.script.annotation.Comment;

import java.util.List;
import java.util.Map;


/**
 * 数据库查询模块
 *
 * @author mxd
 */
@MagicModule("rpcclient")
public class RpcProviderModule  {

    private ApplicationContext applicationContext;

    public RpcProviderModule(ApplicationContext applicationContext){
        this.applicationContext = applicationContext;
    }

    /*
    * 获取调用对象
    * */
    @Comment("获取调用对象")
    public GenericService getGenericService(@Comment("注册中心地址") String address,@Comment("是否鉴权") Boolean isauth,@Comment("用户名") String username,@Comment("密码") String password,@Comment("类名") String interfaceName,@Comment("超时时间")int timeout){
        ApplicationConfig applicationConfig = new ApplicationConfig();
        applicationConfig.setName(applicationContext.getEnvironment().getProperty("spring.application.name"));
        RegistryConfig registryConfig = new RegistryConfig();
        registryConfig.setAddress(address);
        if(isauth){
            registryConfig.setUsername(username);
            registryConfig.setPassword(password);
        }

        ReferenceConfig<GenericService> referenceConfig = new ReferenceConfig<>();
        referenceConfig.setInterface(interfaceName);
        applicationConfig.setRegistry(registryConfig);
        referenceConfig.setApplication(applicationConfig);
        referenceConfig.setGeneric("true");
        if(timeout>0){
            referenceConfig.setTimeout(timeout);
        }else{
            referenceConfig.setTimeout(7000);
        }
        return  referenceConfig.get();
    }

    /*
    *
    * 调用方法
    * */
    @Comment("调用方法")
    public RpcJsonBean invoke(@Comment("调用对象") GenericService genericService, @Comment("方法名") String method, @Comment("参数对象(格式： [{ paramType: 'java.lang.String', paramValues: '123' }])") List<Map<String, Object>> paramList){

        int size = paramList.size();
        String[] paramTypes = new String[size];
        Object[] paramValues = new Object[size];

        for (int i = 0; i < size; ++i) {
            Map<String,Object> param = paramList.get(i);
            String paramType = param.get("paramType").toString();
            Object paramValue = param.get("paramValues");

            paramTypes[i] = paramType;
            paramValues[i] = paramValue;
        }

        return (RpcJsonBean) genericService.$invoke(method, paramTypes, paramValues);
    }


}
